package com.app.twth.ui.mine.version;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.databinding.library.baseAdapters.BR;

import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityVersionBinding;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.io.File;

/**
 * Created by admin on 2024/5/7.
 * Description:
 * Encoding: utf-8
 */
public class VersionActivity extends BaseActivity<ActivityVersionBinding, VersionViewModel> {
    private String TAG = getClass().getSimpleName();

    @Override
    protected void initListener() {
        viewModel.versionLiveData.observe(this, data -> {
            try {
                if (data==null){
                    ToastUtil.showToast("This is the latest version");
                    return;
                }
                String versionCode = data.getVersion();
                if (versionCode.contains(".")) {
                    versionCode = versionCode.replace(".", "");
                }

                String versionName = Utils.getVersionName(mContext);
                if (versionName.contains(".")) {
                    versionName = versionName.replace(".", "");
                }

                int newCode = Integer.parseInt(versionCode);
                int curCode = Integer.parseInt(versionName);

                if ((newCode > curCode)&&data.isUpgrade()) {//有新版本并允许升级
                    viewModel.getApk(data.getUrl(),mContext);
                } else {
                    ToastUtil.showToast("This is the latest version");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        viewModel.fileLiveData.observe(this, data -> {
            setApkFile(data);
        });

        binding.layoutUpdate.setOnClickListener(v -> {
            viewModel.getNewAppInfo();
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setLayoutBottomGone();
        binding.tvVersion.setText("V" + Utils.getVersionName(mContext));
        viewModel.getNewAppInfo();
    }

    @Override
    protected String setTitle() {
        return "Version";
    }

    File apkfile;

    public void setApkFile(File file) {
        apkfile = file;
        installApk();
    }

    //7.在请求安装未知应用来源的权限后
    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 10086) {

            Uri packageURI = Uri.parse("package:com.app.twth");
//            Uri packageURI = Uri.parse("package:" + getPackageName());
            Log.e(TAG, "packageURI:" + packageURI);
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
            startActivityForResult(intent, 457);
        }
    }

    //8.在 startActivityForResult(intent,457);执行后
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 457) {
            if (Build.VERSION.SDK_INT >= 26) {
                if (getPackageManager().canRequestPackageInstalls()) {

                    installApk();
                } else {
                    ToastUtil.showToast("Installation permission is not enabled, installation failed!");
                }
            }
        } else if (requestCode == 1002) {
            if (!Settings.canDrawOverlays(this)) {
                //若未授权则请求权限
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1002);
            }
        }
    }

    //9.安装apk，适配android 7.0
    private void installApk() {
        if (apkfile == null) {
            Log.e(TAG, "1apkfile==null");
            apkfile = new File(getExternalCacheDir().getPath(), "twth.apk");
            Log.e(TAG, "apkfile:" + apkfile.getPath());
        }

        if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(this, "com.app.twth.fileprovider", apkfile);
            Log.e(TAG, "apkUri:" + apkUri);
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(install);
        }
    }
}
